<template>
  <div style>
    <a-tree
      :size="'small'"
      :treeData="placeTree"
      :checkable="checkable"
      @check="onCheck"
      @select="onSelect"
      :checkedKeys="checked"
      :selectedKeys="selected"
      :expandedKeys="iExpandedKeys"
      :autoExpandParent="autoExpandParent"
      @expand="onExpand"
    >
      <template slot="title" slot-scope="{title}">
        <span v-if="title.indexOf(searchValue) > -1">
          {{title.substr(0, title.indexOf(searchValue))}}
          <span style="color: #f50">{{searchValue}}</span>
          {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
        </span>
        <span v-else>{{title}}</span>
      </template>
    </a-tree>
  </div>
</template>

<script>
import place from "@/api/accessControlSystem/place";
export default {
  props: {
      placeTree: Array,
    heightTree: String,
    checkable: Boolean,
    searchValue: String
  },
  data() {
    return {
      autoExpandParent: true, //是否自动展开父节点
      checked: [],
      selected: [],
      treeData: [],
      iExpandedKeys: [],

    };
  },
  mounted() {
    let _this = this;
    // 初始化场所树
    place.getTreeList().then(res => {
      _this.placeTree = res.result;
      console.log(res);
      if (this.placeTree != "") {
        this.iExpandedKeys = [this.placeTree[0].key];
      }
    });
  },
  watch: {
    searchValue: function(newVal, oldVal) {
      console.log(newVal);
      console.log(oldVal);
      this.onSearch(newVal);
    }
  },
  methods: {
    //树形选中
    onCheck(checked) {
      //this.checked = checked 交给父元素去修改数据
      this.$emit("update:checked", checked);
      this.$emit("on-check", checked);
      this.checked = checked;
      this.selected = [];
    },
    // 树形选择
    onSelect(selectedKeys, info) {
      this.$emit("update:selected", selectedKeys);
      this.$emit("on-select", selectedKeys);
      this.$emit("on-select-info", info);
      this.selected = selectedKeys;
      this.checked = [];
      console.log(this.searchValue);
    },
    async onSearch(value) {
      let that = this;
      //根据value过滤树节点符合搜索值得节点，返回相应id数组，赋值给iExpandedKeys
      // 没有这个API?
      let keys = await place.searchDeptByKey({ key: value });

      if (keys.success) {
        that.iExpandedKeys = keys.result;
        // that.searchValue = value;
      }
    },
    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys;
      this.autoExpandParent = false;
    }
  }
};
</script>

<style>
</style>
